<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 面包屑导航 -->
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索和添加用户 -->
        <el-row :gutter="20">
          <el-col :span="10">
            <!-- 搜索 -->
            <el-input
            placeholder="请输入内容"
            v-model="queryData.query"
            clearable
            @clear="fetchUserList"
            >
              <el-button slot="append" icon="el-icon-search" @click="fetchUserList"></el-button>
            </el-input>
          </el-col>
          <!-- 添加 -->
          <el-col :span="4">
             <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- table主体 -->
      <el-table
        :data="userList"
        style="width: 100%" stripe>
        <el-table-column type="index">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- template插槽可接收状态中的值 scale.row -->
          <template slot-scope="scale">
            <el-switch
              v-model="scale.row.mg_state"
              active-color="#13ce66"
              @change="userStateChanged(scale.row)"
              >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="180px">
          <template slot-scope="scale">
             <el-tooltip content="编辑" placement="top">
             <el-button type="primary" icon="el-icon-edit" size="mini"
             @click="editVisibleState(scale.row.id)"
             ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="danger" icon="el-icon-delete" size="mini"
            @click="delUser(scale.row.id)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="分配角色" placement="top" :enterable='false'>
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[1, 2, 3, 5]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      @close='addDialogClosed'
      >
      <el-form :model="addUser" :rules="addUserRules" ref="addUserForm" label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="fetchAddUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="EditDialogVisible"
      width="50%"
      @close="editDialogClosed"
      >
      <el-form :model="editUserInfo" :rules="editUserRules" ref="editUserFormRef" label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="fetchEditUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, toChangeUserState, toAddUser, getUserInfo, delUserInfo } from '@api'
import { MessageBox } from 'element-ui'
// 验证用户名规则
const checkUsername = (rule, value, cb) => {
  const regUsername = /^[a-zA-Z]\w{2,5}$/
  if (!regUsername.test(value)) {
    return cb(new Error('字母开头，数字、字母、下划线组成，3-6位'))
  }
}
// 验证密码规则
const checkPassword = (rule, value, cb) => {
  const regPassword = /^\w{6,12}$/
  if (!regPassword.test(value)) {
    return cb(new Error('6-12位'))
  }
}
// 验证邮箱规则
const checkEmail = (rule, value, cb) => {
  const regEmail = /^([1-9]\d{4,10}@qq|[a-zA-Z]\w{5,17}@(163|126))\.com$/
  if (!regEmail.test(value)) {
    return cb(new Error('字母开头，数字、字母、下划线组成，3-6位'))
  }
}
// 验证电话规则
const checkMobile = (rule, value, cb) => {
  const regMobile = /^1[3456789]\d{9}$/
  if (!regMobile.test(value)) {
    return cb(new Error('请输入正确格式的电话号码'))
  }
}
export default {
  data () {
    return {
      // 发送请求所携带初始数据
      queryData: {
        query: '',
        // 当前页
        pagenum: 1,
        // 页容量
        pagesize: 2
      },
      // 用户列表
      userList: [],
      total: 1,
      // 控制添加用户对话框的显示和隐藏
      dialogVisible: false,
      // 控制编辑用户对话框的显示和隐藏
      EditDialogVisible: false,
      // 表单配置
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑用户信息
      editUserInfo: {},
      // 添加用户表单验证规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户表单验证规则
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取用户信息列表
    fetchUserList () {
      getUserList(this.queryData).then(res => {
        if (res.data.meta.status === 200) {
          this.userList = res.data.data.users
          this.total = res.data.data.total
        }
      })
    },
    // 改变页容量时触发
    handleSizeChange (num) {
      this.queryData.pagesize = num
      this.fetchUserList()
    },
    // 改变当前页
    handleCurrentChange (current) {
      this.queryData.pagenum = current
      this.fetchUserList()
    },
    // 监听状态变化
    userStateChanged (newInfo) {
      toChangeUserState(newInfo.id, newInfo.mg_state).then(res => {
        if (res.data.meta.status === 200) {
          this.$message.success(res.data.meta.msg)
        } else {
          this.$message.error(res.data.meta.msg)
        }
      })
    },
    // 监听添加用户对话框的关闭
    addDialogClosed () {
      // 重置表单
      this.$refs.addUserForm.resetFields()
    },
    // 监听编辑对话框的关闭
    editDialogClosed () {
      // 重置表单
      this.$refs.editUserFormRef.resetFields()
    },
    // 添加用户
    fetchAddUser () {
      this.$refs.addUserForm.validate(valid => {
        if (valid) {
          toAddUser(this.addUser).then(res => {
            if (res.data.meta.status === 200) {
              this.dialogVisible = false
              this.fetchUserList()
            }
          })
        }
      })
    },
    // 编辑验证用户信息并提交
    fetchEditUser () {
      this.$refs.editUserFormRef.validate(valid => {
        if (valid) {
          toAddUser(this.editUserInfo).then(res => {
            if (res.data.meta.status === 200) {
              this.dialogVisible = false
              this.fetchUserList()
            }
          })
        }
      })
    },
    // 获取编辑用户的信息
    editVisibleState (id) {
      getUserInfo(id).then(res => {
        if (res.data.meta.status === 200) {
          this.editUserInfo = res.data.data
        }
      })
      this.EditDialogVisible = true
    },
    // 删除用户
    async delUser (id) {
      const confirmMessage = await MessageBox.confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmMessage !== 'confirm') {
        this.$message.info('已取消删除')
      }
      delUserInfo(id).then(res => {
        if (res.data.meta.status !== 200) {
          this.$message.warning(res.data.meta.msg)
        }
        this.$message.success(res.data.meta.msg)
        this.fetchUserList()
      })
    }
  },
  created () {
    this.fetchUserList()
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  box-shadow: 0 1px 1px rgba(0,0,0,.15) !important;
}
.el-pagination{
  margin-top: 20px;
}
</style>
